//
//  XQKeyChainManager.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/1/27.
//

import Security
import Foundation

class XQKeyChainManager: NSObject {
    
    private static let service = "com.sparkPeso.service"
    
    // 保存数据到 Keychain
    @discardableResult
    static func save(data: String) -> Bool {
        guard let dataToStore = data.data(using: .utf8) else { return false }
        
        // 创建查询字典
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecValueData as String: dataToStore
        ]
        
        // 删除旧数据（如果存在）
        SecItemDelete(query as CFDictionary)
        
        // 添加新数据
        let status = SecItemAdd(query as CFDictionary, nil)
        
        return status == errSecSuccess
    }
    
    // 从 Keychain 加载数据
    static func load() -> String? {
        // 创建查询字典
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecReturnData as String: kCFBooleanTrue!,
            kSecMatchLimit as String: kSecMatchLimitOne
        ]
        
        var result: AnyObject?
        let status = SecItemCopyMatching(query as CFDictionary, &result)
        
        if status == errSecSuccess {
            if let data = result as? Data {
                return String(data: data, encoding: .utf8)
            }
        }
        
        return nil
    }
}
